package com.atom.common.delegate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.activiti.engine.task.Task;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.atom.common.DelegateAction;
import com.atom.common.DelegateStatus;
import com.atom.common.DelegateType;
import com.atom.common.VariablesConstant;
import com.atom.common.activiti.ActivitiHandler;
import com.atom.common.remote.palace.RemoteRunningTaskDao;

/**
 * Title: AddOutDelegateHandler
 * Description: 添加外出代理
 * @author WEWE
 * @date 2017年12月4日 下午3:16:37
 * @version 1.0
 */
@Component
@Transactional
public class AddOutDelegateHandler {

  private static Logger logger = Logger.getLogger(AddOutDelegateHandler.class);

  @Resource DelegateInfoDao delegateInfoDao;
  @Resource DelegateLogDao delegateLogDao;
  @Resource ActivitiHandler activitiHandler;
  @Resource RemoteRunningTaskDao remoteRunningTaskDao;

  public void add(DelegateInfo info) {
    logger.info("DelegateInfo:Id:" + info.getId());
    logger.info("DelegateInfo:DelegateStatus:" + info.getDelegateStatus());
    logger.info("DelegateInfo:Owner:" + info.getOwner());
    logger.info("DelegateInfo:Assignee:" + info.getAssignee());
    List<Map<String, String>> list = new ArrayList<Map<String, String>>();
    // 将状态改为处理中
    info.setDelegateStatus(DelegateStatus.ADD_DOING);
    delegateInfoDao.update(info);
    // 被代理人
    String owner = info.getOwner();
    // 代理人
    String assignee = info.getAssignee();
    // 公文类型
    String processDefKey = info.getProcessDefinitionKey();
    // 获取被代理人的任务列表
    List<Task> taskList = activitiHandler.findTaskListByUserByProcessDefKey(owner, processDefKey);
    for (Task task : taskList) {
      if (task.getAssignee() != null && task.getAssignee().equals(owner)) {
        // 替换任务受理人
        activitiHandler.updateAssignee(task.getId(), assignee);
      } else {
        // 替换任务候选人
        activitiHandler.updateCandidate(task.getId(), owner, assignee);
      }
      // 记录操作日志
      DelegateLog log = new DelegateLog(info.getId(), task.getId(), owner, assignee, DelegateType.OUT);
      delegateLogDao.save(log);
      // 改平台待办表
      Map<String, String> re = new HashMap<String, String>();
      String sysModID = (String) activitiHandler.findVariableByTaskIdByKey(task.getId(), VariablesConstant.SYSTEM_MODULER);
      re.put("ACTIVITYENTITYID", sysModID + "_" + processDefKey + "_" + task.getId());
      re.put("SYSMODID", sysModID);
      re.put("owner", owner);
      re.put("assignee", assignee);
      re.put("delegateType", DelegateType.OUT + "");
      list.add(re);
    }
    // 将状态改为已完成
    info.setDelegateStatus(DelegateStatus.ADD_DONE);
    delegateInfoDao.update(info);
    remoteRunningTaskDao.updateTodoTasksForDelegate(list, DelegateAction.ADD);

  }

}
